/******************************************************************************

	COPYRIGHT(C) JONAS 'SORTIE' TERMANSEN 2010.

	This file is part of Maxsi Engine.

	Maxsi Engine is free software: you can redistribute it and/or modify it
	under the terms of the GNU Lesser General Public License as published by
	the Free Software Foundation, either version 3 of the License, or (at your
	option) any later version.

	Maxsi engine is distributed in the hope that it will be useful, but WITHOUT
	ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
	FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
	for more details.

	You should have received a copy of the GNU Lesser General Public License
	along with Maxsi Engine. If not, see <http://www.gnu.org/licenses/>.

	MaxsiEngine.dll
	A general purpose C++ library for the Maxsi Technology Project.

	MaxsiTime.h
	Functions for dealing with time stuff in a simple and cross-platform
	manner!

******************************************************************************/

#include "MaxsiEngine.h"

BeginMaxsiNamespace

#ifdef WIN32

MaxsiError MaxsiGetSystemTime(Time_t* Time)
{
	*Time = GetTickCount();

	return MAXSI_ERROR_SUCCESS;
}

int SubtractTimes(Time_t* Result, Time_t* x, Time_t* y)
{
	*Result = (*y) - (*x);	

	return 0;
}

double TimeToDouble(Time_t Input)
{
	return ((double)Input)/1000.f;
}

#elif defined(Maxsi_Support_POSIX)

MaxsiError MaxsiGetSystemTime(Time_t* Time)
{
	gettimeofday((struct timeval*)Time, NULL);

	return MAXSI_ERROR_SUCCESS;
}

int SubtractTimes(Time_t* Result, Time_t* x, Time_t* y)
{
	// Perform the carry for the later subtraction by updating y.
	if (x->tv_usec < y->tv_usec)
	{
		int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
		y->tv_usec -= 1000000 * nsec;
		y->tv_sec += nsec;
	}

	if (x->tv_usec - y->tv_usec > 1000000)
	{
		int nsec = (x->tv_usec - y->tv_usec) / 1000000;
		y->tv_usec += 1000000 * nsec;
		y->tv_sec -= nsec;
	}
     
	// Compute the time remaining to wait. tv_usec is certainly positive.
	Result->tv_sec		=	x->tv_sec - y->tv_sec;
	Result->tv_usec		=	x->tv_usec - y->tv_usec;
     
	// Return 1 if result is negative.
	return x->tv_sec < y->tv_sec;
}

double TimeToDouble(Time_t Input)
{
	return (double)(Input.tv_sec*1.0f + Input.tv_usec / 1000000.0f);
}

#endif

EndMaxsiNamespace

